<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学生姓名" prop="stuname">
        <el-input v-model="queryParams.stuname" placeholder="请输入学生姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="身份证号" prop="stucardnumber">
        <el-input v-model="queryParams.stucardnumber" placeholder="请输入学生身份证号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="学生电话" prop="stuphone">
        <el-input v-model="queryParams.stuphone" placeholder="请输入学生电话" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="学生微信" prop="stuwx">
        <el-input v-model="queryParams.stuwx" placeholder="请输入学生微信" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="学生QQ" prop="stuqq">
        <el-input v-model="queryParams.stuqq" placeholder="请输入学生QQ" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="学生地址" prop="stuaddress">
        <el-input v-model="queryParams.stuaddress" placeholder="请输入学生地址" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="监护人" prop="stufamilyname">
        <el-input v-model="queryParams.stufamilyname" placeholder="请输入学生监护人" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="stufamilyphone">
        <el-input v-model="queryParams.stufamilyphone" placeholder="请输入学生监护人手机号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="线索来源" prop="stusource">
        <el-select v-model="queryParams.stusource" filterable allow-create remote :remote-method="remoteSearch"
          placeholder="请输入学生线索来源" clearable @change="handleQuery" size="medium" class="w-full">
          <el-option v-for="item in sourceTypeList" :key="item.id" :label="item.name" :value="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="学生类型" prop="typename">
        <el-select v-model="queryParams.typename" filterable allow-create remote :remote-method="remoteSearch"
          placeholder="请输入或选择学生类型" clearable @change="handleQuery" size="medium" class="w-full">
          <el-option v-for="item in studenttypeList" :key="item.id || item.typename" :label="item.typename"
            :value="item.typename" />
        </el-select>
      </el-form-item>
      <el-form-item label="跟进类型" prop="processName">
        <el-select v-model="queryParams.processName" filterable allow-create remote :remote-method="remoteSearch"
          placeholder="请输入或选择跟进类型" clearable @change="handleQuery" size="medium" class="w-full">
          <el-option v-for="item in recordprogressList" :key="item.id || item.processName" :label="item.processName"
            :value="item.processName" />
        </el-select>
      </el-form-item>
      <div>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <el-button type="primary" plain icon="User" @click="handleAssign"
            v-hasPermi="['studentinfo:studentinfo:assign']">手动分配</el-button>
        </el-form-item>
      </div>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['studentinfo:studentinfo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['studentinfo:studentinfo:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['studentinfo:studentinfo:remove']">删除</el-button>
      </el-col>

      <el-button type="success" plain icon="Check" @click="handleRegistration"
        v-hasPermi="['studentinfo:studentinfo:registration']" class="registration-btn">立即报名
      </el-button>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['studentinfo:studentinfo:export']">导出</el-button>
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="studentinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学生id" align="center" prop="studentid" />
      <el-table-column label="学生姓名" align="center" prop="stuname" />
      <el-table-column label="学生性别" align="center" prop="stusex" />
      <el-table-column label="学生身份证号" align="center" prop="stucardnumber" />
      <el-table-column label="学生电话" align="center" prop="stuphone" />
      <el-table-column label="学生微信" align="center" prop="stuwx" />
      <el-table-column label="学生QQ" align="center" prop="stuqq" />
      <el-table-column label="年龄" align="center" prop="stuage" />
      <el-table-column label="学生地址" align="center" prop="stuaddress" />
      <el-table-column label="监护人名字" align="center" prop="stufamilyname" />
      <el-table-column label="监护人手机号" align="center" prop="stufamilyphone" />
      <el-table-column label="线索来源" align="center" prop="stusource" />
      <el-table-column label="学生类型" align="center" prop="typename" />
      <el-table-column label="跟进类型" align="center" prop="processName" />
      <el-table-column label="状态" align="center" width="80">
        <template #default>
          <el-tag type="success">
            显示
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <el-button link type="success" icon="Check" @click="handleRegistration(row)"
            v-hasPermi="['studentinfo:studentinfo:edit']">
            转为报名
          </el-button>
          <el-button link type="success" icon="Check" @click="handleRecord(row)"
            v-hasPermi="['studentinfo:studentinfo:edit']">
            转为跟进
          </el-button>
          <el-button link type="primary" icon="Edit" @click="handleUpdate(row)"
            v-hasPermi="['studentinfo:studentinfo:edit']">
            修改
          </el-button>
          <el-button link type="danger" icon="Delete" @click="() => handleDelete(row)"
            v-hasPermi="['studentinfo:studentinfo:remove']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改学生信息管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="studentinfoRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学生姓名" prop="stuname">
          <el-input v-model="form.stuname" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="学生电话" prop="stuphone">
          <el-input v-model="form.stuphone" placeholder="请输入学生电话" />
        </el-form-item>
        <el-form-item label="学生类型" prop="stuTypeId">
          <el-select v-model="form.stuTypeId" placeholder="请选择学生类型" clearable>
            <el-option v-for="item in studenttypeList" :key="item.stuTypeId" :label="item.typename"
              :value="item.stuTypeId" />
          </el-select>
        </el-form-item>
        <el-form-item label="线索来源" prop="stusource">
          <el-select v-model="form.stusource" placeholder="请输入学生线索来源" clearable>
            <el-option v-for="item in sourceTypeList" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进进度" prop="recordProgressId">
          <el-input v-model="ProgressName" readonly placeholder="无跟进进度信息" />
        </el-form-item>
        <el-form-item label="学生性别" prop="stusex">
          <el-radio-group v-model="form.stusex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="身份证号" prop="stucardnumber">
          <el-input v-model="form.stucardnumber" placeholder="请输入学生身份证号" />
        </el-form-item>
        <el-form-item label="学生微信" prop="stuwx">
          <el-input v-model="form.stuwx" placeholder="请输入学生微信" />
        </el-form-item>
        <el-form-item label="学生QQ" prop="stuqq">
          <el-input v-model="form.stuqq" placeholder="请输入学生QQ" />
        </el-form-item>
        <el-form-item label="年龄" prop="stuage">
          <el-input v-model="form.stuage" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="学生地址" prop="stuaddress">
          <el-input v-model="form.stuaddress" placeholder="请输入学生地址" />
        </el-form-item>
        <el-form-item label="家长名字" prop="stufamilyname">
          <el-input v-model="form.stufamilyname" placeholder="请输入学生监护人" />
        </el-form-item>
        <el-form-item label="手机号" prop="stufamilyphone">
          <el-input v-model="form.stufamilyphone" placeholder="请输入学生监护人手机号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="assignTitle" v-model="assignDialogVisible" width="500px" append-to-body>
      <el-form ref="assignFormRef" :model="assignForm" :rules="assignRules" label-width="80px">
        <el-form-item label="服务人员" prop="serviceUserId">
          <el-select v-model="assignForm.serviceUserId" placeholder="请选择服务人员" clearable filterable :remote="true"
            :remote-method="remoteSearchServiceUser" :loading="serviceUserLoading" @change="handleServiceUserSelect"
            @focus="loadServiceUsers">
            <el-option v-for="item in serviceUserList" :key="item.userId" :label="item.userName" :value="item.userId">
              <span>{{ item.userName }}</span>
              <span v-if="item.nickName" style="float: right; color: #8492a6; font-size: 13px">
                {{ item.nickName }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAssign">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 报名表单 -->
    <el-dialog class="registration-container" v-model="Registrationopen">
      <el-form ref="studentinfo" :model="form" :rules="rules" label-width="120px" label-position="top">
        <!-- 学生基本信息 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="section-title">学生基本信息</div>
          </template>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学生姓名" prop="stuname">
                <el-input v-model="form.stuname" placeholder="请输入学生姓名" readonly />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="学生性别" prop="stusex">
                <el-radio-group v-model="form.stusex">
                  <el-radio-button disabled label="男" :class="{ 'active-radio': form.stusex === '男' }">
                    男
                  </el-radio-button>
                  <el-radio-button disabled label="女" :class="{ 'active-radio': form.stusex === '女' }">
                    女
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="身份证号" prop="form.stucardnumber">
                <el-input v-model="form.stucardnumber" placeholder="请输入18位身份证号" maxlength="18" show-word-limit
                  readonly />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学生电话" prop="form.stuphone">
                <el-input v-model="form.stuphone" placeholder="请输入手机号码" readonly />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="家庭住址" prop="form.stuaddress">
            <el-input v-model="form.stuaddress" type="textarea" :rows="2" readonly
              :style="{ '::v-deep .el-textarea__inner': { cursor: 'default', backgroundColor: '#f5f7fa' } }" />
          </el-form-item>
        </el-card>

        <!-- 监护人信息 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="section-title">监护人信息</div>
          </template>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="监护人姓名" prop="stufamilyname">
                <el-input v-model="form.stufamilyname" placeholder="无监护人信息" readonly class="readonly-input" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="监护人手机号" prop="stufamilyphone">
                <el-input v-model="form.stufamilyphone" placeholder="无联系电话" readonly class="readonly-input" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <!-- 报名课程 -->
        <el-card class="form-section" shadow="never">
          <template #header>
            <div class="section-title">报名课程</div>
          </template>

          <el-form-item prop="form.course">
            <el-select v-model="form.course" multiple placeholder="请选择报名课程" style="width: 100%" aria-required="true">
              <el-option v-for="course in couresList" :key="course.courseId" :label="course.courseName"
                :value="course.courseId" />
            </el-select>
          </el-form-item>
        </el-card>

        <!-- 提交按钮 -->
        <div class="submit-area">
          <el-button type="primary" size="large" @click="submitRegistration()" :loading="submitting">
            提交报名
          </el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!-- 跟进记录对话框 -->
  <el-dialog :title="title" v-model="ServiceRecord" width="500px" append-to-body>
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="操作人员" >
          <el-input   v-model="userInfo.username"   placeholder="操作人员姓名" readonly/>
        </el-form-item>
        <el-form-item label="学生姓名" prop="stuname">
          <el-input v-model="form.stuname" placeholder="请输入学生姓名"readonly />
        </el-form-item>
        <el-form-item label="学生类型">
          <el-input v-model="studenttypeName" placeholder="请选择学生类型" readonly/>
        </el-form-item>
        <el-form-item label="跟进方式" prop = "recordTypeId">
          <el-select v-model="form.recordTypeId" placeholder="请输入跟进方式" clearable>
            <el-option v-for="item in recordTypeList" :label="item.typeName" :value="item.recordTypeId" />
          </el-select>
        </el-form-item>
        <el-form-item label="记录时间" prop="recordDate">
          <el-date-picker clearable v-model="form.recordDate" type="date" value-format="YYYY-MM-DD"
            placeholder="选择跟踪记录时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="记录内容" prop="recordMsg">
          <el-input v-model="form.recordMsg" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="上传图片" prop="img">
          <image-upload v-model="form.img" />{{ form.img }}
        </el-form-item>
        <el-form-item label="是否重点标记" prop="isMarking">
          <el-input v-model="form.isMarking" placeholder="数字越小，时间越早优先级越高" />
          </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormKey">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>



</template>
<script setup name="Studentinfo">
import { listStudentinfo, getStudentinfo, delStudentinfo, addStudentinfo, updateStudentinfo } from "@/api/student/studentinfo/studentinfo"
import { listStudenttype } from "@/api/student/studenttype/studenttype"
import { listRecordprogress, addRecordprogress } from "@/api/student/recordprogress/recordprogress"
import { addRegistration } from "@/api/registration/registration"
import { getTbcourse, listTbcourse } from "@/api/tbcourse/tbcourse"
import { listService,listUser} from "@/api/system/user"
import { addKeyallocation } from "@/api/keyallocation/keyallocation"
import { addRecord } from "@/api/record/record";
import { listRecordtype } from "@/api/recordtype/recordtype"
import{getUserInfo} from "@/utils/auth"
import { ref } from "vue"
import { get } from "@vueuse/core"
const { proxy } = getCurrentInstance()

const sourceTypeList = ref([
  { id: 1, name: '主动了解', value: 'active' },
  { id: 2, name: '线上聊天', value: 'online' },
  { id: 3, name: '走访', value: 'visit' },
  { id: 4, name: '其他', value: 'other' }
]);
const studentinfoList = ref([])
const recordTypeList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 手动分配相关变量
const assignDialogVisible = ref(false)
const assignTitle = ref('手动分配学生')
const assignForm = ref({
  serviceUserId: null,
  serviceUserName: null
})
const assignRules = ref({
  serviceUserId: [{ required: true, message: '请选择服务人员', trigger: 'blur' }]
})
const serviceUserLoading = ref(false)
const serviceUserList = ref([])
const ProgressName = ref('初始状态')
const data = reactive({
  form: {
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    stuname: null,
    stusex: null,
    stucardnumber: null,
    stuphone: null,
    stuwx: null,
    stuqq: null,
    stuage: null,
    stuaddress: null,
    stufamilyname: null,
    stufamilyphone: null,
    stuschool: null,
    stuterm: null,
    stuspecialized: null,
    stuclass: null,
    sturoom: null,
    stusource: null,
    typename: null,
    processName: null,
    state: null,
    recordProgressId: null,
    stutype: null,
  },
  rules: {
    stuname: [
      { required: true, message: "学生姓名不能为空", trigger: "blur" }
    ],
    stuphone: [
      { required: true, message: "学生电话不能为空", trigger: "blur" }
    ],
    stusource: [
      { required: true, message: "学生线索来源不能为空", trigger: "blur" }
    ],
    stusex: [
      { required: true, message: "学生性别不能为空", trigger: "blur" }
    ],
    stuTypeId: [
      { required: true, message: "学生类型不能为空", trigger: "blur" }
    ],
    recordTypeId: [
      { required: true, message: "跟进方式不能为空", trigger: "blur" }
    ],
   
  }
})

const { queryParams, form, rules } = toRefs(data)
const studenttypeList = ref([])
const recordprogressList = ref([])
const registration = ref([])
const processState = ref(0)
//从Cookie中获取用户信息
const userInfo = getUserInfo()

console.log("用户信息111111111111111", userInfo)
const userList1 = ref([])
const userid=ref('')

// 跟进用户名获取ID
async function getUserId(username) {
  try {
    console.log("用户信息1", username)
    const response = await listUser({ userName: username });
    userList1.value = response.rows;
    console.log("用户信息2", userList1.value);
    
    const user = userList1.value.find(item => item.userName === username);
    console.log("用户信息3", user.userId);
    if (!user) {
      throw new Error(`未找到用户: ${username}`);
    }
    userid.value = user.userId
  } catch (error) {
    console.error("获取用户ID失败", error);
    throw error;
  }
}
getUserId(userInfo.username)
console.log("用户ID", userid.value)
const queryDa = reactive({
  pageNum: 1,
  pageSize: 10,
  typeName: null,
  state: null
})
/** 获取跟进方式列表 */
const getRecordtypeList = () => {
  queryDa.state = 0
  listRecordtype(queryDa).then(response => {
    recordTypeList.value = response.rows
    console.log("跟进方式列表", recordTypeList.value)
  })
}
getRecordtypeList()
// 查询跟进状态列表
async function getRecordProgress() {
  try {
    const response = await listRecordprogress({});
    if (response.code === 200) {
      recordprogressList.value = response.rows;
      console.log("查询跟进状态成功", recordprogressList.value);

      // 查找"初始状态"记录
      const initialState = recordprogressList.value.find(
        item => item.processName === "初始状态"
      );
      console.log("初始状态信息1111:", initialState);
      if (initialState) {
        // 存在初始状态，直接获取ID
        processState.value = initialState.recordProgressId;
        return initialState.recordProgressId;

      } else {
        // 不存在初始状态，插入新记录
        return insertRecordProgress("初始状态");
      }
    } else {
      console.error("查询跟进状态失败:", response.msg);
      throw new Error("查询跟进状态失败");
    }
  } catch (error) {
    console.error("查询跟进状态异常:", error);
    throw error;
  }
}

// 插入跟进状态（返回新记录ID）
async function insertRecordProgress(progressName) {
  try {
    const recordprogress = {
      processName: progressName
    };

    const response = await addRecordprogress(recordprogress);
    if (response.code === 200) {
      console.log("插入跟进状态成功");

      // 插入成功后，重新查询获取ID
      return getRecordProgress();
    } else {
      console.error("插入跟进状态失败:", response.msg);
      throw new Error("插入跟进状态失败");
    }
  } catch (error) {
    console.error("插入跟进状态异常:", error);
    throw error;
  }
}

// 初始化函数（在组件挂载时调用）
async function initRecordProgress() {
  try {
    const initialStateId = await getRecordProgress();
    processState.value = initialStateId;
    console.log("初始化跟进状态完成，ID3333333333:", processState.value);
  } catch (error) {
    proxy.$modal.msgError("初始化跟进状态失败");
  }
}
initRecordProgress();
//转跟进按钮
const studenttypeName = ref('')
const ServiceRecord=ref(false)
function  handleRecord (row){
  reset();
  const _studentid = row.studentid || ids.value
  getStudentinfo(_studentid).then(response => {
    form.value = response.data
    studenttypeName.value = studenttypeList.value.find(item => item.stuTypeId === response.data.stuTypeId).typename
    console.log("学生信息1222222", studenttypeName.value)
    console.log("学生信息111111", form.value)
    ServiceRecord.value=true
    title.value = "添加跟进记录";
  })
 
}
// 转为报名的功能的实现
const Registrationopen = ref(false)
//点击转为报名按钮
async function handleRegistration(row) {
  if (!row.studentid && ids.value.length === 0) {
    proxy.$modal.msgWarning('请先选择一条数据')
    return
  }
  if (ids.value.length > 1) {
    proxy.$modal.msgWarning('请不要多选')
    return
  }
  reset()
  Registrationopen.value = true
  const _studentid = row.studentid || ids.value

  const studentResponse = await getStudentinfo(_studentid);
  form.value = await studentResponse.data;


}

async function submitRegistration() {
  if (form.value.course == null) {
    proxy.$modal.msgWarning('请先选择课程')
    return
  }
  const requests = form.value.course.map(id => getTbcourse(id));
  const results = await Promise.all(requests);
  const prices = results.map(item => Number(item.data.price)) || 0;

  const tbregistration = ref({
    stuId: form.value.studentid,
    userName: form.value.stuname,
    phone: form.value.stuphone,
    emergency: form.value.stufamilyphone,
    stucardnumber: form.value.stucardnumber,
    stufamilyname: form.value.stufamilyname,
    stuaddr: form.value.stuaddress,
    course: form.value.courseId,
    studentSource: '线索池报名',
    courseId: Array.isArray(form.value.course)
      ? form.value.course.join(',')
      : form.value.course || '',
    gender: form.value.stusex === '男' ? 0 : 1,
    payFees: prices.reduce((a, b) => a + b, 0),

  })
  addRegistration(tbregistration.value).then(response => {
    if (response.code === 200) {
      proxy.$modal.msgSuccess("报名成功");
      Registrationopen.value = false
      reset()
      getList()
    } else {
      proxy.$modal.msgError(response.msg)
    }
  })
}

//获取课程的信息
const couresList = ref([]);
const courseParam = reactive({
  pageNum: 1,
  pageSize: 100
});
function getallcouresList() {
  listTbcourse(courseParam).then(response => {
    couresList.value = response.rows
  })
}
getallcouresList()
const userList = ref([])
// 手动分配按钮点击事件
const handleAssign = () => {
  if (ids.value.length === 0) {
    proxy.$modal.msgWarning('请先选择要分配的学生')
    return
  }
  assignForm.value = {
    serviceUserId: null,
    serviceUserName: ''
  }
  assignDialogVisible.value = true
  // 初始化加载服务人员列表
  loadServiceUsers()
}

// 加载服务人员列表
const loadServiceUsers = async () => {
  try {
    serviceUserLoading.value = true
    const response = await listService({})
    serviceUserList.value = response.rows.map(user => ({
      userId: user.userId,
      userName: user.userName,
      nickName: user.nickName
    }))
  } catch (error) {
    console.error('加载服务人员失败:', error)
    proxy.$modal.msgError('加载服务人员列表失败')
  } finally {
    serviceUserLoading.value = false
  }
}

// 远程搜索服务人员
const remoteSearchServiceUser = (query) => {
  serviceUserLoading.value = true
  listService({ username: query }).then(response => {
    serviceUserList.value = response.rows.map(user => ({
      userId: user.userId,
      userName: user.userName // 确保使用userName
    }))
  }).catch(error => {
    console.error('搜索服务人员失败:', error)
    proxy.$modal.msgError('搜索服务人员失败')
  }).finally(() => {
    serviceUserLoading.value = false
  })
}

// 处理选择服务人员
const handleServiceUserSelect = (userId) => {
  const selectedUser = serviceUserList.value.find(item => item.userId === userId)
  if (selectedUser) {
    assignForm.value.serviceUserName = selectedUser.userName
  }
}

const submitAssign = () => {
  proxy.$refs.assignFormRef.validate(valid => {
    if (valid) {
      // 检查是否有选中的学生
      if (!ids.value || ids.value.length === 0) {
        proxy.$modal.msgWarning('请选择要分配的学生');
        return;
      }

      // 过滤出所有选中的学生信息
      const selectedStudents = studentinfoList.value.filter(item =>
        ids.value.includes(item.studentid)
      );

      // 存储成功和失败的数量
      let successCount = 0;
      let failedCount = 0;
      const failedMessages = [];

      loading.value = true;

      // 方案1：串行处理（逐个提交）
      const processNextStudent = (index) => {
        if (index >= selectedStudents.length) {
          // 所有学生处理完毕
          handleFinalResult();
          return;
        }

        const student = selectedStudents[index];
        const params = {
          studentid: student.studentid, // 单个学生ID
          userId: assignForm.value.serviceUserId,
          stuschool: student.stuschool || '',
          stuspecialized: student.stuspecialized || '',
          stuclass: student.stuclass || '',
          stuTypeId: student.stuTypeId || '',
          recordProgressId: 6,
          remarks: `分配学生 ${student.stuname} 给 ${assignForm.value.serviceUserName}`,
          state: 0
        };

        // 执行分配操作
        addKeyallocation(params)
          .then(() => {
            successCount++;
            console.log("student", student)
            // 分配成功后，添加跟进记录
            const recordData = {
              studentid: student.studentid,
              userId: assignForm.value.serviceUserId,
              stutype: student.typename || '',
              recordTypeId: 1, // 假设跟进方式ID为1（可根据实际情况修改）
              recordDate: new Date().toISOString().split('T')[0], // 当前日期
              recordMsg: `成功分配学生 ${student.stuname} 给服务人员 ${assignForm.value.serviceUserName}`,
              isMarking: null,
              state: 0
            };

            // 添加跟进记录
            return addRecord(recordData);
          })
          .then(() => {
            console.log(`为学生 ${student.stuname} 添加跟进记录成功`);
          })
          .catch(error => {
            failedCount++;
            failedMessages.push(`学生 ${student.stuname}: ${error.message || '未知错误'}`);
          })
          .finally(() => {
            // 处理下一个学生
            processNextStudent(index + 1);
          });
      };

      // 开始处理第一个学生
      processNextStudent(0);

      // 处理最终结果
      const handleFinalResult = () => {
        loading.value = false;

        if (successCount > 0) {
          proxy.$modal.msgSuccess(`成功分配 ${successCount} 名学生`);
        }

        if (failedCount > 0) {
          proxy.$modal.msgError(`分配失败 ${failedCount} 名学生`);
          console.error('分配失败详情:', failedMessages);
        }

        // 如果全部成功，关闭对话框
        if (failedCount === 0) {
          assignDialogVisible.value = false;
        }
      };
    }
  });
};
/**查询服务人员列表 */
const getUserList = () => {
  listService().then(response => {
    userList.value = response.rows
  })
}
getUserList();

const queryData = reactive({
  pageNum: 1,
  pageSize: 10,
  typename: null,
  state: null
})
/** 获取学生类型列表 */
const getStudenttypeList = () => {
  queryData.state = 0
  listStudenttype(queryData).then(response => {
    studenttypeList.value = response.rows
  })
}
getStudenttypeList()
const queryDas = reactive({
  pageNum: 1,
  pageSize: 10,
  processName: null,
  state: null
})
/** 获取跟进进度列表 */
const getRecordprogressList = () => {
  queryDas.state = 0
  listRecordprogress(queryDas).then(response => {
    recordprogressList.value = response.rows
  })
}
getRecordprogressList()

/** 查询学生信息管理列表（带日志） */
function getList() {
  loading.value = true;
  // 强制覆盖 state，避免被其他逻辑影响
  queryParams.value.state = 0;
  // console.log("queryParams.value", queryParams.value)
  listStudentinfo(queryParams.value).then(response => {
    studentinfoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 取消按钮
function cancel() {
  open.value = false
  Registrationopen.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    studentid: null,
    stuname: null,
    stusex: null,
    stucardnumber: null,
    stuphone: null,
    stuwx: null,
    stuqq: null,
    stuage: null,
    stuaddress: null,
    stufamilyname: null,
    stufamilyphone: null,
    stuschool: null,
    stuterm: null,
    stuspecialized: null,
    stuclass: null,
    sturoom: null,
    stusource: null,
    typename: null,
    processName: null,
    state: null
  }
  proxy.resetForm("studentinfoRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  console.log("queryParams.value", queryParams.value)
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.studentid)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加学生信息管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _studentid = row.studentid || ids.value
  getStudentinfo(_studentid).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改学生信息管理"
  })
}
/** 跟进记录按钮操作 */
function submitFormKey(){
  console.log("form.value1111111111111", form.value)
  console.log("img",form.value.img)
  const recordData = {
    studentid: form.value.studentid,
    userId: userid.value,
    stutype: studenttypeName.value,
    recordTypeId: form.value.recordTypeId , // 假设跟进方式ID为1（可根据实际情况修改）
    recordDate: new Date().toISOString().split('T')[0], // 当前日期
    recordMsg: form.value.recordMsg,
    img:form.value.img,
    isMarking: null,
    state: 0
  };
  addRecord(recordData).then(response => {
    if (response.code === 200) {
      proxy.$modal.msgSuccess("添加跟进记录成功");
      ServiceRecord.value=false
    } else {
      proxy.$modal.msgError(response.msg)
    }
  })
}

/** 删除按钮操作（逻辑删除） */
function handleDelete(row) {
  let studentIds = [];
  let confirmMessage = '';
  if (row && row.studentid) {
    studentIds = [row.studentid];
    confirmMessage = `是否确认删除学生"${row.stuname}"的记录？`;
  } else if (ids.value.length > 0) {
    studentIds = ids.value;
    const selectedCount = ids.value.length;
    confirmMessage = `是否确认删除选中的${selectedCount}条学生记录？`;
  } else {
    proxy.$modal.msgWarning("请选择要删除的记录");
    return;
  }

  proxy.$modal.confirm(confirmMessage).then(async () => {
    try {
      loading.value = true;
      await Promise.all(studentIds.map(id => {
        return updateStudentinfo({
          studentid: id,
          state: 1
        });
      }));
      studentinfoList.value = studentinfoList.value.filter(
        item => !studentIds.includes(item.studentid)
      );

      proxy.$modal.msgSuccess("删除成功");
    } catch (error) {
      // 关键：打印错误信息，定位问题
      console.error("删除失败:", error);
      proxy.$modal.msgError("删除失败: " + (error.message || "未知错误"));
    } finally {
      loading.value = false;
      ids.value = [];
      single.value = true;
      multiple.value = true;
    }
  }).catch(() => { });
}
// 提交表单
const submitForm = () => {
  proxy.$refs.studentinfoRef.validate(valid => {
    if (valid) {
      if (form.value.studentid != null) {
        // 修改操作
        updateStudentinfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        // 新增操作
        form.value.recordProgressId = processState.value;
        console.log("222222222", form.value)
        addStudentinfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}
function handleExport() {
  // 构造导出专用参数，只保留需要的其他查询条件（如分页、姓名等），去掉 state
  const exportParams = {
    stuname: queryParams.value.stuname

  };
  proxy.download(
    'studentinfo/studentinfo/export',
    exportParams,
    `studentinfo_${new Date().getTime()}.xlsx`
  );
}

getList()
</script>
